﻿using AntMovement.Comm.Helper;
using AntMovement.Comm.Model;
using AntMovement.Core.LabelService;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AntMovement.Comm
{
    /// <summary>
    /// 校验
    /// </summary>
    public class Verify : IChainedHandle
    {
        private Func<int, OutTimeModel> _query;
        public Func<int, OutTimeModel> Query => _query;
        private Func<int, bool, bool> _updateTime;
        public Func<int, bool, bool> UpdateTime => _updateTime;
        private IChainedHandle[] _chainedHandles;
        private ITagManager _tagManager;

        public Verify(ITagManager tagManager, Func<int, OutTimeModel> query, Func<int, bool, bool> updateTime)
        {
            _tagManager = tagManager;
            _query = query;
            _updateTime = updateTime;
            _chainedHandles = new IChainedHandle[]
            {
                new Enrollment(query, updateTime),
                new Exit(query, updateTime),
                new Read(_tagManager, query, updateTime),
                new Write(_tagManager, query, updateTime),
            };
        }

        public void Execute(byte[] request, List<byte> respond)
        {
            int length = (request[6] + (request[7] << 8)) + 8;
            respond.Add(0x58);
            respond.Add(0x4C);
            if (length == request.Length && request[0] == 0x58 && request[1] == 0x4C) 
            {
                try
                {
                    switch (request[10])
                    {
                        case 0x60:
                            _chainedHandles[0].Execute(request, respond);
                            break;
                        case 0x61:
                            _chainedHandles[1].Execute(request, respond);
                            break;
                        case 0x4C:
                            _chainedHandles[2].Execute(request, respond);
                            break;
                        case 0x4D:
                            _chainedHandles[3].Execute(request, respond);
                            break;
                    }
                }
                catch (Exception)
                {
                    respond.Clear(); 
                    respond.Add(0x58);
                    respond.Add(0x4C);
                    respond.Add(request[2]);
                    respond.Add(request[3]);
                    respond.Add(request[4]);
                    respond.Add(request[5]);
                    respond.AddRange(BytesHelper.ToUnknown(request[10]));
                }
            }
            else
            {
                respond.AddRange(new byte[4]);
                respond.AddRange(new byte[2] { 3, 0});
                respond.Add(0x04);
                respond.Add(0x00);
                respond.Add(request[10]);
            }
        }
    }
}
